//
//  UserPasswordVC.m
//  huien
//
//  Created by yiban on 2017/5/26.
//  Copyright © 2017年 lcb. All rights reserved.
//

#import "UserPasswordVC.h"
#import "UserModifyPasswordVC.h"
@interface UserPasswordVC ()<UITextFieldDelegate>
{
    
}

@property (weak) id<LcbLoginDelegate> delegate;
@property(nonatomic,strong) UIScrollView *scrollview;
@property(nonatomic,strong) UITextField     *txtPhone;
@property(nonatomic,strong) UITextField     *txtPhoneCer;
@property(nonatomic,strong) UIButton     *loginBtn;
@property(nonatomic,strong) UIButton     *registerBtn;
@property(nonatomic,strong) NSString *sessionID;
+ (instancetype)newController;
@end

@implementation UserPasswordVC
@synthesize sessionID=_sessionID;
+ (instancetype)newController
{
    return [super new];
}
+ (instancetype)newWithDelegate:(id<LcbLoginDelegate>)delegate
{
    UserPasswordVC *viewController = [UserPasswordVC newController];
    
    if (viewController) {
        viewController.delegate = delegate;
    }
    
    return viewController;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navTitle=@"找回密码";
    [self initUI];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    [self handleSingleTapFrom];
    self.txtPhone=nil;
    self.txtPhoneCer=nil;
    self.loginBtn=nil;
    self.registerBtn=nil;
    
}
- (UIScrollView*)scrollview
{
    if (!_scrollview) {
        _scrollview =[[UIScrollView alloc] initWithFrame:CGRectMake(0, YB_HeaderHeight, SCREEN_WIDTH, SCREEN_HEIGHT-YB_HeaderHeight)];
        _scrollview.backgroundColor=[UIColor clearColor];
        UITapGestureRecognizer* singleRecognizer= [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTapFrom)];
        _scrollview.userInteractionEnabled =YES;
        [_scrollview addGestureRecognizer:singleRecognizer];
        singleRecognizer=nil;
    }
    return _scrollview;
}
-(UITextField *)txtPhone
{
    if (!_txtPhone) {
        _txtPhone = [[UITextField alloc] initWithFrame:CGRectZero];
        _txtPhone.placeholder = @"请输入您的手机号";
        _txtPhone.font = [UIFont systemFontOfSize:13];
        [_txtPhone setValue:h2color forKeyPath:@"_placeholderLabel.textColor"];
        _txtPhone.autocorrectionType = UITextAutocorrectionTypeNo;
        _txtPhone.autocapitalizationType = UITextAutocapitalizationTypeNone;
        _txtPhone.returnKeyType = UIReturnKeyNext;
        _txtPhone.clearButtonMode = UITextFieldViewModeWhileEditing;
        _txtPhone.delegate=self;
        _txtPhone.leftView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_phone"]];
        _txtPhone.leftViewMode=UITextFieldViewModeAlways; //此处用来设置leftview现实时机
        _txtPhone.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        
        
    }
    return _txtPhone;
}
-(UITextField *)txtPhoneCer
{
    if (!_txtPhoneCer) {
        _txtPhoneCer = [[UITextField alloc] initWithFrame:CGRectZero];
        _txtPhoneCer.placeholder = @"请输入收到的验证码";
        _txtPhoneCer.font = [UIFont systemFontOfSize:13];
        [_txtPhoneCer setValue:h2color forKeyPath:@"_placeholderLabel.textColor"];
        _txtPhoneCer.autocorrectionType = UITextAutocorrectionTypeNo;
        _txtPhoneCer.autocapitalizationType = UITextAutocapitalizationTypeNone;
        _txtPhoneCer.returnKeyType = UIReturnKeyNext;
        _txtPhoneCer.clearButtonMode = UITextFieldViewModeWhileEditing;
        _txtPhoneCer.delegate=self;
        _txtPhoneCer.leftView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_code"]];
        _txtPhoneCer.leftViewMode=UITextFieldViewModeAlways; //此处用来设置leftview现实时机
        _txtPhoneCer.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        _txtPhoneCer.rightView = self.loginBtn;
        _txtPhoneCer.rightViewMode=UITextFieldViewModeAlways; //此处用来设置leftview现实时机
    }
    return _txtPhoneCer;
}
-(UIButton*)loginBtn
{
    if (!_loginBtn) {
        _loginBtn =[UIButton buttonWithType:UIButtonTypeRoundedRect];
        _loginBtn.backgroundColor =codecolor;
        _loginBtn.layer.cornerRadius = 30/2;
        _loginBtn.tag=0;
        [_loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_loginBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_loginBtn addTarget:self action:@selector(loginbtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_loginBtn];
    }
    return _loginBtn;
}
-(UIButton*)registerBtn
{
    if (!_registerBtn) {
        _registerBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        _registerBtn.backgroundColor =btncolor;
        _registerBtn.layer.cornerRadius = 45/2;
        _registerBtn.tag= 1;
        [_registerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_registerBtn setTitle:@"找回密码" forState:UIControlStateNormal];
        [_registerBtn addTarget:self action:@selector(loginbtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_registerBtn];
    }
    return _registerBtn;
}
-(void)loginbtnClick:(id)sender
{
    UIButton *btn =(UIButton*)sender;
    switch (btn.tag) {
        case 0:
        {
            if(self.txtPhone.text.length==0)
            {
                [YBToast showWithText:@"请输入您的手机号"];
                return;
            }
            NSMutableDictionary *dict =[NSMutableDictionary dictionary];
            [dict setValue:self.txtPhone.text forKey:@"phone"];
            
            __weak typeof(self) weakSelf = self;
            [HEApi smsPwdWithParam:dict serviceblock:^(id response, NSString *errorMsg) {
                if (response) {
                    LcbBaseModel *baseModel = (LcbBaseModel*)response;
                    if (baseModel.code==0) {
                        [weakSelf makeTimer];
                    }
                }
                
            }];
        }
            break;
        case 1:
        {
            [self btnLoginAction];
        }
            break;
            
        default:
            break;
    }
}
#pragma mark - 发送 短信，收取验证码
- (void)makeTimer{
    __weak typeof(self) weakSelf = self;
    __block int timeOut = 60;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (timeOut <= 0) {
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.loginBtn setTitle:@"重新获取" forState:UIControlStateNormal];
                weakSelf.loginBtn.userInteractionEnabled = YES;
            });
        }
        else {
            int second = timeOut % 89 == 00 ? timeOut : timeOut % 89;
            NSString *strtime = [NSString stringWithFormat:@"%.2d",second];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.loginBtn setTitle:[NSString stringWithFormat:@"%@秒",strtime] forState:UIControlStateNormal];
                weakSelf.loginBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
                weakSelf.loginBtn.userInteractionEnabled = NO;
            });
            timeOut--;
        }
    });
    dispatch_resume(timer);
}
-(void)handleSingleTapFrom
{
    if ([self.txtPhone isFirstResponder]) {
        [self.txtPhone resignFirstResponder];
    }
    if ([self.txtPhoneCer isFirstResponder]) {
        [self.txtPhoneCer resignFirstResponder];
    }
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (textField==self.txtPhone) {
        [self.txtPhone becomeFirstResponder];
    }else if (textField==self.txtPhoneCer){
        [textField resignFirstResponder];
    }else
    {
        [textField resignFirstResponder];
    }
    return YES;
}
-(void)initUI
{
    //
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 20, 60, 44);
    backButton.tag =100;
    [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [backButton addTarget:self action:@selector(clickNavEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:backButton];
    //
    [self.scrollview setContentSize:CGSizeMake(0, SCREEN_HEIGHT)];
    
    [self.view addSubview:self.scrollview];
    self.txtPhone.frame =CGRectMake(20, 20, SCREEN_WIDTH-40, 40);
    UIView *lineView1 = [[UIView alloc]initWithFrame:CGRectMake(0,self.txtPhone.height - 1, self.txtPhone.width, 1)];
    lineView1.backgroundColor = linecolor;
    [self.txtPhone addSubview:lineView1];
    [self.scrollview addSubview:self.txtPhone];
    //
    self.loginBtn.frame=CGRectMake(0, 0, 100, 30);
    //
    self.txtPhoneCer.frame =CGRectMake(self.txtPhone.frame.origin.x, self.txtPhone.frame.origin.y+self.txtPhone.frame.size.height+20,  SCREEN_WIDTH-40, 40);
    UIView *lineView2 = [[UIView alloc]initWithFrame:CGRectMake(0,self.txtPhoneCer.height - 1, self.txtPhoneCer.width, 1)];
    lineView2.backgroundColor = linecolor;
    [self.txtPhoneCer addSubview:lineView2];
    [self.scrollview addSubview:self.txtPhoneCer];
    //
    self.registerBtn.frame=CGRectMake(self.txtPhoneCer.frame.origin.x, self.txtPhoneCer.frame.origin.y+self.txtPhoneCer.frame.size.height+45, SCREEN_WIDTH-40, 45);
    [self.scrollview addSubview:self.registerBtn];
    
}
-(void)clickNavEvent:(id)sender
{
    UIButton *btn =(UIButton*)sender;
    switch (btn.tag) {
        case 100:
        {
            if (self.navigationController) {
                if (self.navigationController.viewControllers.count == 1) {
                    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                } else {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
            break;
        case 101:
        {
            
        }
            break;
        default:
            break;
    }
    
}

- (void)btnLoginAction
{
    if(self.txtPhone.text.length==0)
    {
        [YBToast showWithText:@"请输入您的手机号"];
        return;
    }
    if(self.txtPhoneCer.text.length==0)
    {
        [YBToast showWithText:@"请输入收到的验证码"];
        return;
    }
    __weak typeof (self) wSelf = self;
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:self.txtPhone.text forKey:@"phone"];
    [dict setValue:self.txtPhoneCer.text forKey:@"code"];
    
    [HEApi byphoneWithParam:dict serviceblock:^(id response, NSString *errorMsg) {
        if (response) {
            LcbBaseModel *sessionModel = (LcbBaseModel*)response;
            if (sessionModel.code==0) {
                UserModifyPasswordVC *reg =[UserModifyPasswordVC newWithDelegate:_delegate];
                reg.phone =wSelf.txtPhone.text;
                [wSelf.navigationController pushViewController:reg animated:YES];
            }else{
                [YBToast showWithText:sessionModel.message];
            }
        }
        
    }];
   
    
}
@end
